/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.client.gui.standalone.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;

import javax.swing.JTextArea;

/**
 * Redirect the text of standard output on jTextArea
 * 
 */
public class JTextAreaStream {
	
	private JTextArea area;

	public void redirectSystemOutputTo(JTextArea textArea) throws IOException {
		area = textArea;
		Pipe pipe = Pipe.open();
		OutputStream out = Channels.newOutputStream(pipe.sink());
		final InputStream in = Channels.newInputStream(pipe.source());
			Runnable task = new Runnable() {
			
			public void run() {
			    loopRead(in);
			}
		};
		System.setOut(new PrintStream(out));
		Thread reader = new Thread(task, "Stream reader");
		reader.setDaemon(true);
		reader.start();
	}

	private void loopRead(InputStream stream) {
	    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
	    String line = null;
		try {
            while ((line = in.readLine()) != null) {
            	appendLine(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
	}

	private void appendLine(final String text) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
    				area.append(text);
    				area.append("\n");
//		        }
//		});
    }
}